﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace BingWallpaper
{

    public class AutoRun
    {
        private static readonly string runKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
        public static string AppName { get; set; } = AppDomain.CurrentDomain.FriendlyName;
        public static string AppPath { get; set; } = Process.GetCurrentProcess().MainModule.FileName;
        public static string Args { get; set; } = $"--auto";
        private static string KeyValue { get; set; } = $"\"{AppPath}\" {Args}";

        public static bool State
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(runKey, true);
                try
                {
                    var runKeyValue = Convert.ToString(key?.GetValue(AppName));
                    return runKeyValue != null && runKeyValue.Contains(AppPath);
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    key.Close();
                }
            }
            set
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(runKey, true);
                try
                {
                    if (value)
                    {
                        key.SetValue(AppName, KeyValue);
                    }
                    else
                    {
                        key.DeleteValue(AppName);
                    }
                }
                finally
                {
                    key.Close();
                }
            }
        }


    }
}
